package com.yilian.xlmusic.android;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProviders;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.minlukj.mediaplaylib.MediaPlayerUtils;
import com.yilian.xlmusic.android.base.MyApplication;
import com.yilian.xlmusic.android.base.MyBaseActivity;
import com.yilian.xlmusic.android.base.MyFragmentPagerAdapter;
import com.yilian.xlmusic.android.databinding.ActivityMainBinding;
import com.yilian.xlmusic.android.utils.HistoryRecord;
import com.yilian.xlmusic.android.utils.MeasureUnitTranUtil;
import com.yilian.xlmusic.android.utils.ViewAnimator;
import com.yilian.xlmusic.android.utils.net.AppConstants;
import com.yilian.xlmusic.android.view.CollectionMusicFragment;
import com.yilian.xlmusic.android.view.FoundMusicFragment;
import com.yilian.xlmusic.android.view.SearchFragment;
import com.yilian.xlmusic.android.view.bean.ChangeItem;
import com.yilian.xlmusic.android.view.bean.MusicBean;
import com.yilian.xlmusic.android.view.bean.SharedMessage;
import com.yilian.xlmusic.android.view.bean.SharedViewModel;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import rxhttp.RxHttp;

public class XlMusicActivity extends MyBaseActivity{
    private SharedViewModel model;
    private Fragment current_fragment;
    private ArrayList<Fragment> list;
    private boolean flag = false;
    public static  String TAG=XlMusicActivity.class.getName();
    public static MediaPlayerUtils mMediaPlayerUtils;
    private ActivityMainBinding binding;
    @Override
    public int getNetType() {
        return 0;
    }

    @Override
    public int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView(Bundle var1) {
        MyApplication.addDestoryActivity(this,XlMusicActivity.TAG);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
        mMediaPlayerUtils = new MediaPlayerUtils();

        showDialog();
        setTitleView();

        setTabLayout();

        initFragment();

        initListener();

        getNetResource();
    }

    private void getNetResource() {
        AppConstants.METHOD_NAME = "首页数据：";
        RxHttp.get("/ylmusic-gateway/home")
                .addHeader(AppConstants.ACCESS_TOKEN_KEY, AppConstants.ACCESS_TOKEN)
                .asClass(MusicBean.class)
                .observeOn(AndroidSchedulers.mainThread())  //主线程回调观察者
                .subscribe(result -> {
                    setBanner(result.getData().getBanners());
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            closeDialog();
                            binding.foudMusicView.setVisibility(View.VISIBLE);
                        }
                    },500);

                }, throwable -> {
                    Log.e("请求失败了", "请求失败了" + throwable);
                });
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        model.getSelected().observe(list.get(0).getViewLifecycleOwner(), value -> {
            if (value.getType() == 0) {
                binding.searchText.setText(value.getValue());
            }
            if (value.getType() == 3) {
                flag = true;
                binding.searchText.setText(value.getValue());
            }

        });

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {//点击editText控件外部
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    assert v != null;
                    hideInput();

                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        return getWindow().superDispatchTouchEvent(ev) || onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }

    private void initListener() {
        model = ViewModelProviders.of(XlMusicActivity.this).get(SharedViewModel.class);
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;         // 屏幕宽度（像素）
        int dip2px = MeasureUnitTranUtil.dip2px(XlMusicActivity.this, 45);
        binding.searchClose.setOnClickListener(v -> binding.searchText.setText(""));
        binding.searchText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                //为RelativeLayout设置宽高
                if (hasFocus) {
                    Log.e("第一次计算", String.valueOf(width - dip2px));
                    ViewAnimator.doAnim( binding.searchFoot, "width", width, width - dip2px);
                    //显示布局
                    binding.searchFrame.setVisibility(View.VISIBLE);
                    binding.foudMusicView.setVisibility(View.GONE);
                }
            }

        });
        binding.mainClose.setOnClickListener(v -> finish());
        binding.searchBack.setOnClickListener(v -> {
            if (binding.searchText != null) {
                binding.searchText.clearFocus();
                binding.searchText.setText("");
            }
            ViewAnimator.doAnim(binding.searchFoot, "width", width - dip2px, width);
            binding.searchFrame.setVisibility(View.GONE);
            binding.foudMusicView.setVisibility(View.VISIBLE);
            mMediaPlayerUtils.stop();
            //更新适配器的内容
            if (AppConstants.changeItems.size() > 0) {
                refreshView(AppConstants.changeItems.get(0));
            }
        });

        binding.searchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    binding.searchClose.setVisibility(View.VISIBLE);
                } else {
                    binding.searchClose.setVisibility(View.INVISIBLE);
                }
                if (flag) {
                    flag = false;
                    return;
                }
                SharedMessage message = new SharedMessage();
                message.setType(1);
                message.setValue(s.toString());
                model.select(message);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        binding.searchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (binding.searchText.length() > 0) {
                        //点击搜索的时候隐藏软键盘
                        hideInput();
                        //写入历史记录
                        HistoryRecord.saveSearchHistory(XlMusicActivity.this, binding.searchText.getText().toString());
                        // 在这里写搜索的操作,网络请求数据
                        SharedMessage message = new SharedMessage();
                        message.setType(2);
                        message.setValue(binding.searchText.getText().toString());
                        model.select(message);
                        return true;
                    } else {
                        return false;
                    }

                }

                return false;
            }
        });
        binding.viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //fragment刷新
//                mMediaPlayerUtils.stop();
                if (position == 1) {
                    SharedMessage message = new SharedMessage();
                    message.setType(4);
                    model.select(message);
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    public void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    private void initFragment() {
        list = new ArrayList<>();
        SearchFragment fragment = new SearchFragment();
        list.add(fragment);

        startFragmentAdd(list.get(0));
    }

    private void startFragmentAdd(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        if (current_fragment == null) {
            fragmentTransaction.add(R.id.searchFrame, fragment).commit();
            current_fragment = fragment;
        }
        if (current_fragment != fragment) {
            // 先判断是否被add过
            if (!fragment.isAdded()) {
                // 隐藏当前的fragment，add下一个到Activity中
                fragmentTransaction.hide(current_fragment)
                        .add(R.id.searchFrame, fragment).commit();
            } else {
                // 隐藏当前的fragment，显示下一个
                fragmentTransaction.hide(current_fragment).show(fragment)
                        .commit();
            }
            current_fragment = fragment;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        //更新适配器的内容
        if (AppConstants.changeItems.size() > 0) {
            AppConstants.refreshView(AppConstants.changeItems.get(0));
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //更新适配器的内容
        if (AppConstants.changeItems.size() > 0) {
            AppConstants.refreshView(AppConstants.changeItems.get(0));
        }
    }

    private void refreshView(ChangeItem refresh_item) {
        refresh_item.getDataBean().setIs_play(!refresh_item.getDataBean().isIs_play());
        refresh_item.setDataBean(refresh_item.getDataBean());
        refresh_item.getItemRecycleViewAdapter().getData().set(refresh_item.getChangePosition(), refresh_item.getDataBean());
        refresh_item.getItemRecycleViewAdapter().notifyItemChanged(refresh_item.getChangePosition(), refresh_item.getDataBean());
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMediaPlayerUtils.destory();
        mMediaPlayerUtils = null;
    }

    private void setTitleView() {
        hideTitleBar();
        setIsFullScreen(true, true, R.color.color_000000);
        setStatusBarTextColor2(Color.parseColor("#000000"));
        setBackEnable(false);
    }

    private void setTabLayout() {
        String[] titles = new String[]{"发现音乐", "我的收藏"};
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(new FoundMusicFragment());
        fragments.add(new CollectionMusicFragment());
        MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
        pagerAdapter.setItems(fragments);
        binding.viewPager.setAdapter(pagerAdapter);
        binding.viewPager.setNoScroll(false);//禁止滑动
        binding.tabView.setViewPager(binding.viewPager, titles);
        binding.tabView.setCurrentTab(0);
    }

    private void setBanner(List<MusicBean.DataBean.BannersBean> banners) {

        binding.banner.setAdapter(new BannerImageAdapter<MusicBean.DataBean.BannersBean>(banners) {
            @Override
            public void onBindView(BannerImageHolder holder, MusicBean.DataBean.BannersBean data, int position, int size) {
                Glide.with(holder.itemView)
                        .load(data.getCover())
                        .apply(RequestOptions.bitmapTransform(new RoundedCorners(30)))
                        .into(holder.imageView);
            }
        })
                .addBannerLifecycleObserver(this)
                .setIndicator(new CircleIndicator(this));
        binding.banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(Object data, int position) {
                //Log.e("点击了", "" + position);
            }
        });


    }
}